<template>
  <div class="statistics bg-gradient-to-br from-blue-50 to-cyan-100 h-screen overflow-hidden p-4">
    <!-- 主内容区域：图表和表格 -->
    <div class="flex flex-col gap-4 h-full overflow-hidden">
      <!-- 第二部分：图表 -->
      <div class="glass-card rounded-2xl p-4 shadow-lg overflow-hidden flex-1">
        <div class="flex justify-between items-center mb-2">
          <h2 class="text-lg font-bold text-gray-800">测站状态统计图表</h2>
          <!-- 搜索条件 -->
          <div class="rounded-lg">
            <div class="flex items-center gap-1">
              <div>
                <CustomSelect
                  v-model="searchForm.monitorType" 
                  placeholder="监测类型"
                  style="width: 180px;"
                  :clearable="false"
                  :optionList="dataItems"
                  @on-change="typeChange" />
              </div>
            </div>
          </div>
        </div>
        <div ref="chartContainer" class="w-full h-full"></div>
      </div>

      <!-- 第三部分：表格 -->
      <div class="glass-card rounded-2xl p-4 shadow-lg overflow-hidden flex-1">
        <h2 class="text-lg font-bold text-gray-800 mb-2">测站状态统计表</h2>
        <div ref="tableContainer" class="overflow-auto h-full">
          <CustomTable
            ref="JTable"
            :columns="columns"
            :stripe="true"
            :is-pages="false"
            :isAutoLoad="false"
            :border="true"
            :height="tableHeight" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts/core';
import {
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components';
import { BarChart, LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import { mapState } from 'vuex';
import { dataItems } from 'common/js/modules';
import { columns } from './js/modules';
import { isEmpty } from 'lodash-es';

echarts.use([
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  LineChart,
  CanvasRenderer,
  UniversalTransition
]);

export default {
  name: 'Statistics',
  computed: {
    ...mapState({
      total: state => state.home.total,
      totalInventory: state => state.home.totalInventory,
      totalList: state => state.home.totalList,
    })
  },
  created () {
    this.chart = null
    this.dataItems = dataItems()
    this.columns = columns()
  },
  mounted() {
    // 确保DOM渲染完成后再初始化图表
    setTimeout(() => {
      this.initChart();
      // 计算表格初始高度
      this.calculateTableHeight();
      // 添加窗口大小改变事件监听器
      window.addEventListener('resize', this.handleResize);
    }, 20);
  },
  beforeUnmount() {
    // 销毁图表实例
    if (this.chart) {
      this.chart.dispose();
    }
    // 移除窗口大小改变事件监听器
    window.removeEventListener('resize', this.handleResize);
  },
  data() {
    return {
      searchForm: {
        monitorType: 'realtimeSz'
      },
      tableHeight: 0, // 动态计算高度
    }
  },
  methods: {
    initData () {
      const type = this.searchForm.monitorType
      const total = this.total[type]
      const totalList = this.totalList[type]

      if (!total) {
        setTimeout(() => {
          this.initData()
        }, 20)
        return
      }

      if (totalList) {
        const data = {
          '全市': JSON.parse(JSON.stringify(total)),
          '440604': {},
          '440605': {},
          '440606': {},
          '440608': {},
          '440607': {}
        }
        let tableData = []
        let defaultXiang = {}

        switch (type) {
          case 'realtimeSz':
          case 'realtimeBz':
            defaultXiang = {
              '全部': 0,
              '水情正常率': 0,
              '工情正常率': 0,
              '视频正常率': 0,
              '水情正常': 0,
              '水情延迟': 0,
              '水情缺失': 0,
              '工情正常': 0,
              '工情缺失': 0,
              '视频全部在线': 0,
              '视频部分在线': 0,
              '视频全部离线': 0,
              '视频缺失': 0,
            }

            totalList.map(item => {
              const areaName = item['addvcd']

              if (areaName) {
                if (isEmpty(data[areaName])) {
                  data[areaName] = JSON.parse(JSON.stringify(defaultXiang))
                }
  
                data[areaName]['全部'] += 1
                data[areaName][`水情${item.__custom_levelStatus}`] += 1
                data[areaName][`工情${item.__custom_detailStatus}`] += 1
                data[areaName][`视频${item.__custom_videoDetailStatus}`] += 1
              }
            })

            Object.keys(data).forEach(areaName => {
              data[areaName]['水情正常率'] = (data[areaName]['水情正常'] / data[areaName]['全部'] * 100).toFixed(2)
              data[areaName]['工情正常率'] = (data[areaName]['工情正常'] / data[areaName]['全部'] * 100).toFixed(2)
              data[areaName]['视频正常率'] = ((data[areaName]['视频全部在线'] + data[areaName]['视频部分在线']) / data[areaName]['全部'] * 100).toFixed(2)
            })

            tableData = Object.keys(defaultXiang).map(xiangItem => {
              return {
                name: xiangItem,
                city: data['全市'][xiangItem] + (xiangItem === '水情正常率' || xiangItem === '工情正常率' || xiangItem === '视频正常率' ? '%' : ''),
                cc: data['440604'][xiangItem] + (xiangItem === '水情正常率' || xiangItem === '工情正常率' || xiangItem === '视频正常率' ? '%' : ''),
                nh: data['440605'][xiangItem] + (xiangItem === '水情正常率' || xiangItem === '工情正常率' || xiangItem === '视频正常率' ? '%' : ''),
                sd: data['440606'][xiangItem] + (xiangItem === '水情正常率' || xiangItem === '工情正常率' || xiangItem === '视频正常率' ? '%' : ''),
                gm: data['440608'][xiangItem] + (xiangItem === '水情正常率' || xiangItem === '工情正常率' || xiangItem === '视频正常率' ? '%' : ''),
                ss: data['440607'][xiangItem] + (xiangItem === '水情正常率' || xiangItem === '工情正常率' || xiangItem === '视频正常率' ? '%' : ''),
              }
            })
            break;
          default:
            defaultXiang = {
              '全部': 0,
              '正常率': 0,
              '正常': 0,
              '数据延迟': 0,
              '数据缺失': 0,
            }

            totalList.map(item => {
              const areaName = item['addvcd']

              if (areaName) {
                if (isEmpty(data[areaName])) {
                  data[areaName] = JSON.parse(JSON.stringify(defaultXiang))
                }
  
                data[areaName]['全部'] += 1
                if (item.status === '正常' || item.status === '数据缺失') {
                  data[areaName][`${item.status}`] += 1
                } else {
                  data[areaName]['数据延迟'] += 1
                }
              }
            })

            Object.keys(data).forEach(areaName => {
              if (data[areaName]['全部'] > 0) {
                data[areaName]['正常率'] = (data[areaName]['正常'] / data[areaName]['全部'] * 100).toFixed(2)
              } else {
                data[areaName]['正常率'] = '0'
              }
            })

            tableData = Object.keys(defaultXiang).map(xiangItem => {
              return {
                name: xiangItem,
                city: data['全市'][xiangItem] + (xiangItem === '正常率' ? '%' : ''),
                cc: (data['440604'][xiangItem] || '0') + (xiangItem === '正常率' ? '%' : ''),
                nh: (data['440605'][xiangItem] || '0') + (xiangItem === '正常率' ? '%' : ''),  
                sd: (data['440606'][xiangItem] || '0') + (xiangItem === '正常率' ? '%' : ''),
                gm: (data['440608'][xiangItem] || '0') + (xiangItem === '正常率' ? '%' : ''),
                ss: (data['440607'][xiangItem] || '0') + (xiangItem === '正常率' ? '%' : ''),
              }
            })
            break;
        }
        
        this.renderChart({ data }); 
        this.renderTable({ data: tableData }); 
      }
    },
    initChart() {
      // 确保DOM元素存在后再初始化图表
      if (this.$refs.chartContainer) {
        // 销毁已存在的图表实例
        if (this.chart) {
          this.chart.dispose();
        }
        // 初始化图表
        this.chart = echarts.init(this.$refs.chartContainer);

        this.initData()
      }
    },
    renderChart({ data }) {
      // 确保图表实例存在
      if (!this.chart) return;

      const areaNameArr = ['全市', '440604', '440605', '440606', '440608', '440607']

      const szbzSeries = [
        {
          name: '测站总数',
          type: 'bar',
          itemStyle: { color: '#5070dd' },
          data: areaNameArr.map(areaName => data[areaName]['全部'])
        },
        {
          name: '水情正常',
          type: 'bar',
          itemStyle: { color: '#b6d635' },
          stack: 'Sq',
          data: areaNameArr.map(areaName => data[areaName]['水情正常'])
        },
        {
          name: '水情延迟',
          type: 'bar',
          itemStyle: { color: '#ff994d' },
          stack: 'Sq',
          data: areaNameArr.map(areaName => data[areaName]['水情延迟'])
        },
        {
          name: '水情缺失',
          type: 'bar',
          itemStyle: { color: '#ee4779' },
          stack: 'Sq',  
          data: areaNameArr.map(areaName => data[areaName]['水情缺失'])
        },
        {
          name: '工情正常',
          type: 'bar',
          itemStyle: { color: '#0da8df' },
          stack: 'Gq',
          data: areaNameArr.map(areaName => data[areaName]['工情正常'])
        },
        {
          name: '工情缺失',
          type: 'bar',
          itemStyle: { color: '#ffd10c' },
          stack: 'Gq',
          data: areaNameArr.map(areaName => data[areaName]['工情缺失'])
        },
        {
          name: '视频全部在线',
          type: 'bar',
          itemStyle: { color: '#4caf50' }, // 绿色
          stack: 'Sp',
          data: areaNameArr.map(areaName => data[areaName]['视频全部在线'])
        },
        {
          name: '视频部分在线',
          type: 'bar',
          itemStyle: { color: '#ffc107' }, // 琥珀色
          stack: 'Sp',
          data: areaNameArr.map(areaName => data[areaName]['视频部分在线'])
        },
        {
          name: '视频全部离线',
          type: 'bar',
          itemStyle: { color: '#f44336' }, // 红色
          stack: 'Sp',
          data: areaNameArr.map(areaName => data[areaName]['视频全部离线'])
        },
        {
          name: '视频缺失',
          type: 'bar',
          itemStyle: { color: '#9e9e9e' }, // 灰色
          stack: 'Sp',  
          data: areaNameArr.map(areaName => data[areaName]['视频缺失'])
        },
        {
          name: '水情正常率',
          type: 'line',
          yAxisIndex: 1,
          itemStyle: { color: '#b6d635' },
          tooltip: {
            valueFormatter: function (value) {
              return value + '%';
            }
          },
          data: areaNameArr.map(areaName => data[areaName]['水情正常率'])
        },
        {
          name: '工情正常率',
          type: 'line',
          yAxisIndex: 1,
          itemStyle: { color: '#0da8df' },
          tooltip: {
            valueFormatter: function (value) {
              return value + '%';
            }
          },
          data: areaNameArr.map(areaName => data[areaName]['工情正常率'])
        },
        {
          name: '视频正常率',
          type: 'line',
          yAxisIndex: 1,
          itemStyle: { color: '#4caf50' },
          tooltip: {
            valueFormatter: function (value) {
              return value + '%';
            }
          },
          data: areaNameArr.map(areaName => data[areaName]['视频正常率']) 
        }
      ] 

      const otherSeries = [
        {
          name: '测站总数',
          type: 'bar',
          itemStyle: { color: '#5070dd' },
          data: areaNameArr.map(areaName => data[areaName]['全部'])
        },
        {
          name: '测站正常数',
          type: 'bar',
          itemStyle: { color: '#b6d635' },
          stack: 'CeZhanStatus',
          data: areaNameArr.map(areaName => data[areaName]['正常'])
        },
        {
          name: '测站延迟数',
          type: 'bar',
          itemStyle: { color: '#ff994d' },
          stack: 'CeZhanStatus',
          data: areaNameArr.map(areaName => data[areaName]['数据延迟'])
        },
        {
          name: '测站缺失数',
          type: 'bar',
          itemStyle: { color: '#ee4779' },
          stack: 'CeZhanStatus',
          data: areaNameArr.map(areaName => data[areaName]['数据缺失'])
        },
        {
          name: '数据正常率',
          type: 'line',
          yAxisIndex: 1,
          itemStyle: { color: '#0da8df' },
          tooltip: {
            valueFormatter: function (value) {
              return value + '%';
            }
          },
          data: areaNameArr.map(areaName => data[areaName]['正常率'])
        }
      ]

      const type = this.searchForm.monitorType
      const series = (type === 'realtimeSz' || type === 'realtimeBz') ? szbzSeries : otherSeries
  
      // 图表配置
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          position: function (point) {
            // 固定在顶部
            return [point[0], 0];
          }
        },
        legend: {
          top: 'top'
        },
        grid: {
          left: '3%',
          right: '4%',
          top: '20%',
          bottom: '15%'
        },
        xAxis: [
          {
            type: 'category',
            data: ['全市', '禅城区', '南海区', '顺德区', '高明区', '三水区']
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '数量',
          },
          {
            type: 'value',
            name: '正常率',
            min: 0,
            max: 100,
            interval: 10,
            axisLabel: {
              formatter: '{value}%'
            }
          }
        ],
        series
      };
      
      // 渲染图表
      this.chart.setOption(option, true);
    },
    renderTable ({ data }) {
      this.$refs.JTable.tableData = data
    },
    typeChange () {
      this.initData()
    },
    handleResize() {
      // 窗口大小改变时重新调整图表大小
      if (this.chart) {
        this.chart.resize();
      }
      // 重新计算表格高度
      this.calculateTableHeight();
    },
    calculateTableHeight() {
      // 使用 nextTick 确保 DOM 更新完成后再计算高度
      this.$nextTick(() => {
        const tableContainer = this.$refs.tableContainer;
        if (tableContainer) {
          // 获取表格容器的父元素
          const parentElement = tableContainer.parentElement;
          if (parentElement) {
            // 获取父元素的计算样式
            const computedStyle = window.getComputedStyle(parentElement);
            const parentPaddingTop = parseFloat(computedStyle.paddingTop) || 0;
            const parentPaddingBottom = parseFloat(computedStyle.paddingBottom) || 0;
            
            // 获取标题元素的高度
            const titleElement = parentElement.querySelector('h2');
            const titleHeight = titleElement ? titleElement.offsetHeight : 0;
            const titleMarginBottom = titleElement ? 
              (parseFloat(window.getComputedStyle(titleElement).marginBottom) || 0) : 0;
            
            // 计算父元素的可用高度
            const parentRect = parentElement.getBoundingClientRect();
            const parentHeight = parentRect.height;
            
            // 计算表格可用高度（父元素高度 - 内边距 - 标题高度 - 标题下边距 - 一些额外间距）
            const availableHeight = parentHeight - parentPaddingTop - parentPaddingBottom - titleHeight - titleMarginBottom - 10;
            
            // 设置表格高度，最小值为200px
            this.tableHeight = Math.max(200, availableHeight);
          }
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.statistics {
  width: 100%;
  height: 100%;
  .glass-card {
    background: rgba(255, 255, 255, 0.7);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.3);
    box-shadow: 0 8px 32px rgba(31, 38, 135, 0.1);
  }
  
  // 表格样式优化
  table {
    font-size: 0.875rem; // 14px
  }
  
  th, td {
    padding: 0.5rem; // 8px
  }
  
  // 响应式调整
  @media (max-width: 768px) {
    .flex-col.md\:flex-row {
      flex-direction: column;
    }
  }
}
</style>
